<template>
  <Dialog
    v-model="dialogVisible"
    width="620px"
    :title="t('sn.scan_code')"
    :before-close="() => closeDialog(formRef)"
    :close-on-click-modal="true"
    class="sn-dialog"
  >
    <el-form
      :model="form"
      ref="formRef"
      :rules="rules as FormRules"
      label-width="88px"
      class="mx-16px px-15px mb-50px"
    >
      <el-form-item :label="t('sn.related_warehouse')" prop="wid">
        <el-tree-select
          v-model="form.wid"
          :data="warehouseList"
          :disabled="started"
          :render-after-expand="false"
        />
      </el-form-item>
      <el-form-item :label="t('sn.change_operation')" prop="action">
        <el-select
          v-model="form.action"
          :placeholder="t('common.selectText')"
          filterable
          @change="handleActionChange"
        >
          <el-option
            v-for="item in actionList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer v-if="!started">
      <el-button class="m-r-4" @click="closeDialog(formRef)">{{ t('common.cancel') }} </el-button>
      <el-button type="primary" @click="submit(formRef)">{{ t('order.confirm') }} </el-button>
    </template>
    <div
      class="flex flex-col items-center relative bg-#409EFF overflow-hidden rounded-t-8px"
      v-if="started"
    >
      <img src="@/assets/imgs/sn.webp" class="absolute top-0 left-0 right-0 mx-auto" />
      <div class="w-full pt-112px flex flex-col items-center min-h-200px z-9">
        <el-input
          ref="inputRef"
          v-model="form.sn_id"
          :placeholder="t('common.inputText')"
          @keydown.enter="handleEnter"
          class="h-56px"
          style="width: 460px"
        />
        <div
          v-if="snList && snList.length"
          class="max-h-114px overflow-y-auto flex flex-col items-center py-12px rounded-4px w-460px mt-112px mb-70px bg-#fff"
          style="border: 1px solid #e5e7ee"
        >
          <span v-for="(item, index) in snList" :key="index" class="py-8px"
            >SN: {{ item.sn_id }}&nbsp;&nbsp;&nbsp;&nbsp;{{ item.create_time }}&nbsp;&nbsp;{{
              item.action
            }}</span
          >
        </div>
      </div>
    </div>
  </Dialog>
</template>
<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import dayjs from 'dayjs'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
import { getScanCodeApi } from '@/api/snManage'
import { getEnumApi } from '@/api/warehouse/merchandiseOffers'
// import { useDebounceFn } from '@vueuse/core'
const emit = defineEmits(['refresh'])
const { t } = useI18n()
const dialogVisible = ref<boolean>(false)
const started = ref<boolean>(false)
const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  wid: '',
  action: '',
  sn_id: ''
})
const snList = ref<any>([])
const inputRef = ref()
// 表单验证规则
const rules = ref<FormRules>({
  wid: [
    {
      required: true,
      message: t('common.inputText'),
      trigger: ['blur']
    }
  ],
  action: [
    {
      required: true,
      message: t('common.selectText'),
      trigger: ['blur']
    }
  ]
})

const actionList = ref<any>([])
const warehouseList = ref<any>([])
const getSelectList = async () => {
  const resp = await getEnumApi({ field: 'all' })
  warehouseList.value = resp.data.warehouse_parent_tree
}
onMounted(() => {
  getSelectList()
})
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        started.value = true
      } catch (error) {}
    }
  })
}
// 添加输入事件处理
const count = ref(0)
// const handleInput = useDebounceFn((value: string) => {
//   if (value && value.length > 10) { // 假设SN码长度大于10才处理
//     handleEnter()
//   }
// }, 300)
// 添加回车事件处理函数
const handleEnter = async () => {
  try {
    count.value++
    console.log(
      `扫描次数是 ${count.value} 值是${form.value.sn_id} `,
      dayjs(new Date()).format('YYYY-MM-DD 00:00:00')
    )
    const sn_id = form.value.sn_id // 先保存原始值
    if (!sn_id) return
    form.value.sn_id = '' // 清空输入框
    nextTick(() => inputRef.value?.focus()) // 重新聚焦
    const resp = await getScanCodeApi({ ...form.value, sn_id })
    if (resp && resp.code === 0) {
      ElMessage.success(t('common.success'))
      snList.value.push({
        create_time: dayjs(new Date()).format('YYYY-MM-DD 00:00:00'),
        action: actionList.value.find((item) => item.value === form.value.action)?.label,
        sn_id: sn_id
      })
    }
  } catch (error) {
  } finally {
    form.value.sn_id = ''
  }
}
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    wid: '',
    action: '',
    sn_id: ''
  }
  formEl.resetFields()
  dialogVisible.value = false
  emit('refresh')
}
const handleActionChange = () => {
  form.value.sn_id = ''
  if (started.value) {
    inputRef.value?.focus()
  }
}
// 当started变为true时自动聚焦输入框
watch(started, (newVal) => {
  if (newVal) {
    nextTick(() => {
      inputRef.value?.focus()
    })
  }
})
defineExpose({
  dialogVisible,
  started,
  actionList
})
</script>
<style lang="less">
.sn-dialog {
  padding-right: 0 !important;
  padding-bottom: 0 !important;
  padding-left: 0 !important;

  .el-dialog__header {
    margin-right: 16px !important;
    margin-left: 16px !important;
  }

  .el-dialog__footer {
    padding-bottom: 16px !important;
    margin-right: 16px !important;
    margin-left: 16px !important;
  }

  .el-dialog__body {
    padding-right: 0 !important;
    padding-bottom: 0 !important;
    padding-left: 0 !important;

    .el-scrollbar {
      height: initial !important;
    }
  }
}
</style>
